﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TinyForum.DataObjects;
using Apworks.Repositories;
using TinyForum.Infrastructure;
using TinyForum.Domain.Model;
using Apworks.Specifications;

namespace TinyForum.Application.Implementation
{
    public class PostApplication : IPostApplication
    {
        #region IPostApplication Members

        public PostDetailDataObject GetPostDetail(long postId)
        {
            using (RepositoryContextManager mgr = new RepositoryContextManager())
            {
                IRepository<Post> postRepository = mgr.GetRepository<Post>();
                IRepository<Reply> replyRepository = mgr.GetRepository<Reply>();
                IRepository<Account> userRepository = mgr.GetRepository<Account>();
                ISpecification<Post> postSpecification = Specification<Post>.Eval(p => p.ID == postId);
                ISpecification<Reply> repliesSpecification = Specification<Reply>.Eval(r => r.PostID == postId);
                Post post = postRepository.Get(postSpecification);
                Account postUser = userRepository.Get(Specification<Account>.Eval(u => u.ID == post.UserID));
                IEnumerable<Reply> replies = replyRepository.FindAll(repliesSpecification);
                List<Tuple<Reply, Account>> repliesWithUser = new List<Tuple<Reply, Account>>();
                foreach (var reply in replies)
                {
                    Account replyUser = userRepository.Get(Specification<Account>.Eval(u => u.ID == reply.UserID));
                    repliesWithUser.Add(new Tuple<Reply, Account>(reply, replyUser));
                }
                return DataObjectMapper.MapToDataObject(post, postUser, repliesWithUser);
            }
        }

        #endregion
    }
}
